package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

import static com.sky.constant.AutoFillConstant.*;

@Aspect
@Component
public class AutoFillAspect {
    @Pointcut("@annotation(com.sky.annotation.AutoFill)")
    private void pt(){}

    @Before("pt()")
    public void autofill(JoinPoint joinPoint){

        //方法签名对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        //获取注解对象
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);

        //获取数据库操作类型
        OperationType value = annotation.value();

        //获取操作实体对象
        Object[] args = joinPoint.getArgs();
        if(args.length==0){
            return;
        }
        Object entity = args[0];

        //准备赋值数据
        LocalDateTime time = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();

        //根据不同数据库类型，为对应的属性通过反射赋值
        if(value==OperationType.INSERT){
            try {

                Method setCreateTime = entity.getClass().getMethod(SET_CREATE_TIME, LocalDateTime.class);
                Method setUpdateTime = entity.getClass().getMethod(SET_UPDATE_TIME,LocalDateTime.class);
                Method setCreateUser = entity.getClass().getMethod(SET_CREATE_USER,Long.class);
                Method setUpdateUser = entity.getClass().getMethod(SET_UPDATE_USER,Long.class);

                setCreateTime.invoke(entity,time);
                setUpdateTime.invoke(entity,time);
                setCreateUser.invoke(entity,currentId);
                setUpdateUser.invoke(entity,currentId);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else if (value==OperationType.UPDATE){
            try {
                Method setUpdateTime = entity.getClass().getMethod(SET_UPDATE_TIME,LocalDateTime.class);
                Method setUpdateUser = entity.getClass().getMethod(SET_UPDATE_USER,Long.class);

                setUpdateTime.invoke(entity,time);
                setUpdateUser.invoke(entity,currentId);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
